package com.sandasai.service.impl;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.sandasai.dao.AdminDao;
import com.sandasai.domain.Mark;
import com.sandasai.dao.MarkDao;
import com.sandasai.dao.NoticeDao;
import com.sandasai.dao.SettingDao;
import com.sandasai.dao.StudentDao;
import com.sandasai.dao.TeacherDao;
import com.sandasai.dao.UserDao;
import com.sandasai.dao.WorkDao;
import com.sandasai.dao.WorktypeDao;
import com.sandasai.domain.Admin;
import com.sandasai.domain.Notice;
import com.sandasai.domain.Setting;
import com.sandasai.domain.Student;
import com.sandasai.domain.Teacher;
import com.sandasai.domain.User;
import com.sandasai.domain.Work;
import com.sandasai.service.AdminManager;
import com.sandasai.vo.MarkBean;
import com.sandasai.vo.PageBean;
import com.sandasai.vo.SettingBean;
import com.sandasai.vo.StudentBean;
import com.sandasai.vo.TeacherBean;
import com.sandasai.vo.UserBean;
@Service("adminManager")
@Transactional
public class AdminManagerImpl implements AdminManager {
    @Resource
    private UserDao userDao;
    @Resource
    private StudentDao studentDao;
    @Resource
    private TeacherDao teacherDao;
    @Resource
    private AdminDao adminDao;
    @Resource
    private WorktypeDao worktypeDao;
    @Resource
    private WorkDao workDao;
    @Resource
    private MarkDao markDao;
    @Resource
    private SettingDao settingDao;
    @Resource
    private NoticeDao noticeDao;
    
    @Override
    public boolean postNotice(String noticeContent) {
        Notice notice = new Notice();
        notice.setContent(noticeContent);
        notice.setPostDate(new Timestamp(new Date().getTime()));
        noticeDao.save(notice);
        return true;
    }
    @Override
    public String getNoticeContent() {
        List<Notice> notices = noticeDao.findAll();
        if(notices.size() == 0) {
            return "";
        }else {
            return notices.get(notices.size() - 1).getContent();
        }
    }
    @Override
    public boolean setTime(String startTimeOfRegistration,
            String endTimeOfRegistration, String startTimeOfSubmission,
            String endTimeOfSubmission) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        try {
            Date sTR = sdf.parse(startTimeOfRegistration);
            Date eTR = sdf.parse(endTimeOfRegistration);
            Date sTS = sdf.parse(startTimeOfSubmission);
            Date eTS = sdf.parse(endTimeOfSubmission);
            Setting setting = new Setting();
            setting.setStartTimeOfRegistration(new Timestamp(sTR.getTime()));
            setting.setEndTimeOfRegistration(new Timestamp(eTR.getTime()));
            setting.setStartTimeOfSubmission(new Timestamp(sTS.getTime()));
            setting.setEndTimeOfSubmission(new Timestamp(eTS.getTime()));
            settingDao.save(setting);
            return true;
        } catch (ParseException e) {
            e.printStackTrace();
            return false;
        }
    }
    @Override
    public String getStartTimeOfRegistration() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        List<Setting> settings = settingDao.findAll();
        if(settings.size() == 0) {
            return "";
        }else {
            Setting setting = settings.get(settings.size() - 1);
            Date date = new Date(setting.getStartTimeOfRegistration().getTime());
            return sdf.format(date);
        }
    }
    @Override
    public String getEndTimeOfRegistration() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        List<Setting> settings = settingDao.findAll();
        if(settings.size() == 0) {
            return "";
        }else {
            Setting setting = settings.get(settings.size() - 1);
            Date date = new Date(setting.getEndTimeOfRegistration().getTime());
            return sdf.format(date);
        }
    }
    @Override
    public String getStartTimeOfSubmission() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        List<Setting> settings = settingDao.findAll();
        if(settings.size() == 0) {
            return "";
        }else {
            Setting setting = settings.get(settings.size() - 1);
            Date date = new Date(setting.getStartTimeOfSubmission().getTime());
            return sdf.format(date);
        }
    }
    @Override
    public String getEndTimeOfSubmission() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        List<Setting> settings = settingDao.findAll();
        if(settings.size() == 0) {
            return "";
        }else {
            Setting setting = settings.get(settings.size() - 1);
            Date date = new Date(setting.getEndTimeOfSubmission().getTime());
            return sdf.format(date);
        }
    }
    @Override
    public SettingBean getSettingBean() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        SettingBean settingBean = new SettingBean();
        List<Setting> settings = settingDao.findAll();
        if(settings.size() > 0) {
            Setting setting = settings.get(settings.size() - 1);
            settingBean.setStartTimeOfRegistration(sdf.format(new Date(setting.getStartTimeOfRegistration().getTime())));
            settingBean.setEndTimeOfRegistration(sdf.format(new Date(setting.getEndTimeOfRegistration().getTime())));
            settingBean.setStartTimeOfSubmission(sdf.format(new Date(setting.getStartTimeOfSubmission().getTime())));
            settingBean.setEndTimeOfSubmission(sdf.format(new Date(setting.getEndTimeOfSubmission().getTime())));
        }
        return settingBean;
    }
    @Override
    public boolean addAdmin(UserBean userBean) {
        User user = new User();
        user.setUsername(userBean.getUsername());
        user.setPassword(userBean.getPassword());
        user.setEmail(userBean.getEmail());
        user.setRegistrationDate(new Timestamp(new Date().getTime()));
        user.setEmailVerified(false);
        Admin admin = new Admin();
        admin.setUser(user);
        user.setAdmin(admin);
        userDao.save(user);
        return true;
    }
    @Override
    public boolean addTeacher(UserBean userBean) {
        User user = new User();
        user.setUsername(userBean.getUsername());
        user.setPassword(userBean.getPassword());
        user.setEmail(userBean.getEmail());
        user.setRegistrationDate(new Timestamp(new Date().getTime()));
        user.setEmailVerified(false);
        Teacher teacher = new Teacher();
        teacher.setUser(user);
        user.setTeacher(teacher);
        userDao.save(user);
        return true;
    }
   
    @Override
    public PageBean queryForPageWork(int pageSize,int page){
		final String hql = "from Mark";
		//final String hql = "select User.id,User.username,User.password,User.email,User.emailVerified,User.registrationDate from Admin inner join User";
		int allRow = this.markDao.getAllRowCount(hql);
		int totalPage = PageBean.countTotalPage(pageSize, allRow);
		final int offset = PageBean.countOffset(pageSize, page);
		final int length = pageSize;
		final int currentPage = PageBean.countCurrentPage(page);
		List<Mark> list = this.markDao.queryForPage(hql, offset, length);
		PageBean pageBean = new PageBean();
		pageBean.setPageSize(pageSize);
		pageBean.setCurrentPage(currentPage);
		pageBean.setAllRow(allRow);
		pageBean.setTotalPage(totalPage);
		pageBean.setList(list);
		pageBean.init();
		return pageBean;
	}
    @Override
    public PageBean queryForPage(int pageSize,int page){
		final String hql = "select u from User u,Admin a where u.id=a.id";
		//final String hql = "select User.id,User.username,User.password,User.email,User.emailVerified,User.registrationDate from Admin inner join User";
		int allRow = this.adminDao.getAllRowCount(hql);
		int totalPage = PageBean.countTotalPage(pageSize, allRow);
		final int offset = PageBean.countOffset(pageSize, page);
		final int length = pageSize;
		final int currentPage = PageBean.countCurrentPage(page);
		List<Admin> list = this.adminDao.queryForPage(hql, offset, length);
		PageBean pageBean = new PageBean();
		pageBean.setPageSize(pageSize);
		pageBean.setCurrentPage(currentPage);
		pageBean.setAllRow(allRow);
		pageBean.setTotalPage(totalPage);
		pageBean.setList(list);
		pageBean.init();
		return pageBean;
	}
    @Override
    public StudentBean findByStuId(int id){
    	try {
    		User user = (User) userDao.findById(id);
    		Student student = user.getStudent();
    		StudentBean studentBean = new StudentBean();
    		if(user.getBankcard() == null) {
    			studentBean.setBankCardId("");
    		}else {
    			studentBean.setBankCardId(user.getBankcard().getBankCardNum());
    		}
    		studentBean.setCollege(student.getCollege());
    		studentBean.setGrade(student.getGrade());
    		studentBean.setOtherInfo(student.getOtherInfo());
    		studentBean.setRealName(student.getRealName());
    		studentBean.setStudentNo(student.getStudentNo());
    		studentBean.setTel(student.getTel());
    		return studentBean;
    	}catch(Exception e) {
    		e.printStackTrace();
    		return null;
    	}
	}
    @Override
	public TeacherBean findByTeaId(int id){
    	try {
    		User user = (User) userDao.findById(id);
    		Teacher teacher = user.getTeacher();
    		TeacherBean teacherBean = new TeacherBean();
    		if(user.getBankcard() == null) {
    			teacherBean.setBankCardId("");
    		}else {
    			teacherBean.setBankCardId(user.getBankcard().getBankCardNum());
    		}
    		teacherBean.setJobId(teacher.getJobId());
    		teacherBean.setPosition(teacher.getPosition());
    		teacherBean.setRealName(teacher.getRealName());
    		teacherBean.setTel(teacher.getTel());
    		teacherBean.setWorkUnit(teacher.getWorkUnit());
    		return teacherBean;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
    @Override
	public Admin findByAdminId(int id){
		User user = (User) userDao.findById(id);
		Admin admin = user.getAdmin();
		
		return admin;
	}
	@Override
	public void distributeWorks() {
		System.out.println("2");
		List<Work> works = workDao.findAll();
		List<Teacher> teachers = teacherDao.findAll();
		Iterator<Work> iter = works.iterator();
		while(iter.hasNext()){
			Iterator<Teacher> iter2 = teachers.iterator();
			while(iter.hasNext() && iter2.hasNext()){
				Teacher teacher = iter2.next();
				Work work = iter.next();
				Mark mark = new Mark();
				mark.setTeacher(teacher);
				mark.setWork(work);
				mark.setComment("ok");
				mark.setScore(0.01);
				if(!markDao.contain(mark))
					markDao.save(mark);
				System.out.println("3");
			}
		}
		if(teachers.size() > 1){
			iter = works.iterator();
			teachers.add(teachers.get(0));
			teachers.remove(0);
			while(iter.hasNext()){
				Iterator<Teacher> iter2 = teachers.iterator();
				while(iter.hasNext() && iter2.hasNext()){
					Teacher teacher = iter2.next();
					Work work = iter.next();
					Mark mark = new Mark();
					mark.setTeacher(teacher);
					mark.setWork(work);
					mark.setComment("ok");
					mark.setScore(0.01);
					if(!markDao.contain(mark))
						markDao.save(mark);
					System.out.println("3");
				}
			}
		}
	}
	
	
	
	//分页显示数据
	@Override
		public PageBean queryForPageSt(int pageSize,int page){
			final String hql = "select u from User u,Student s where u.id = s.id";
			//final String hql = "select User.id,User.username,User.password,User.email,User.emailVerified,User.registrationDate from Admin inner join User";
			int allRow = this.adminDao.getAllRowCount(hql);
			int totalPage = PageBean.countTotalPage(pageSize, allRow);
			final int offset = PageBean.countOffset(pageSize, page);
			final int length = pageSize;
			final int currentPage = PageBean.countCurrentPage(page);
			List<User> list = this.userDao.queryForPage(hql, offset, length);
			
			/*for(User st:list){
				st.setIsPass(this.userDao.findById(st.getId()).getStudent().getIsPass());
			}*/
			
			PageBean pageBean = new PageBean();
			pageBean.setPageSize(pageSize);
			pageBean.setCurrentPage(currentPage);
			pageBean.setAllRow(allRow);
			pageBean.setTotalPage(totalPage);
			pageBean.setList(list);
			pageBean.init();
			return pageBean;
		}
	//分页显示数据
	@Override
		public PageBean queryForPageTeach(int pageSize,int page){
			final String hql = "select u from User u,Teacher t where u.id=t.id";
			//final String hql = "select User.id,User.username,User.password,User.email,User.emailVerified,User.registrationDate from Admin inner join User";
			int allRow = this.adminDao.getAllRowCount(hql);
			int totalPage = PageBean.countTotalPage(pageSize, allRow);
			final int offset = PageBean.countOffset(pageSize, page);
			final int length = pageSize;
			final int currentPage = PageBean.countCurrentPage(page);
			List<Teacher> list = this.teacherDao.queryForPage(hql, offset, length);
			PageBean pageBean = new PageBean();
			pageBean.setPageSize(pageSize);
			pageBean.setCurrentPage(currentPage);
			pageBean.setAllRow(allRow);
			pageBean.setTotalPage(totalPage);
			pageBean.setList(list);
			pageBean.init();
			return pageBean;
		}
	@Override
	public boolean deleteAdmin(int id){
		User user = new User();
		user = userDao.findById(id);
		if(user == null)
			return false;
		userDao.delete(user.getId());
		//Admin admin = adminDAO.findById(id);
		//adminDAO.delete(admin);
		return true;
	}
	@Override
	public boolean deleteTeacher(int id){
		User user = new User();
		user = userDao.findById(id);
		if(user == null)
			return false;
		userDao.delete(user.getId());
		//Admin admin = adminDAO.findById(id);
		//adminDAO.delete(admin);
		return true;
	}
	@Override
	public boolean deleteStudent(int id){
		User user = new User();
		user = userDao.findById(id);
		if(user == null)
			return false;
		userDao.delete(user.getId());
		//Admin admin = adminDAO.findById(id);
		//adminDAO.delete(admin);
		return true;
	}
	@Override
	public void setStudentState(int id,int isPass){
		User user = this.userDao.findById(id);
		Student st = user.getStudent();
		st.setVerified(true);
		this.studentDao.update(st);
		System.out.println("更新状态成功");
	}
}